//
//  BXPersonDataVoiceVC.m
//  BXlive
//
//  Created by mac on 2020/8/25.
//  Copyright © 2020 cat. All rights reserved.
//

#import "BXPersonDataVoiceVC.h"
#import "DynRecoderVoice.h"
#import "DynPlayMp3Voice.h"
#import "BXDynAlertRemoveSoundView.h"
#import "BXDynCircleProgressView.h"
#import "BXPersonDataRecordVoiceView.h"
#import <FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h>
#import <Masonry/Masonry.h>
#import <SLDeveloperTools/SLDeveloperTools.h>
#import <MMKV/MMKV.h>
#import <YYCategories/YYCategories.h>
#import <SDAutoLayout/SDAutoLayout.h>

@interface BXPersonDataVoiceVC ()<playDelegate>
@property (nonatomic , strong) UIView * navView;
@property (strong, nonatomic) UIButton *backBtn;
@property (strong, nonatomic) UIButton *issueBtn;

//@property(nonatomic, strong)DynRecoderVoice *recoderSound;
@property(nonatomic, strong)DynPlayMp3Voice *playSound;
//@property (nonatomic,strong)NSTimer *recordTimer;

//@property(nonatomic, strong)UIView *micrBackView;
//@property(nonatomic, strong)UIImageView *MicrImageView;
//
//@property(nonatomic, strong)UIButton *micrAniImageView;
//@property(nonatomic, strong)UIButton *micrAniPlaybtn;
//@property(nonatomic, strong)UILabel *micrAnilabel;
//@property(nonatomic, strong)UIButton *micrdeleteBtn;
//@property(nonatomic, strong)UIButton *micrSaveimageBtn;
//
//
//@property(nonatomic, strong)BXDynCircleProgressView *circleView;
//@property(nonatomic, strong)UILabel *Duralabel;
@property (strong, nonatomic) NSString *mp3Path;
//@property (assign, nonatomic) NSInteger timeRecoder;
//@property (assign, nonatomic) NSInteger initRecoder;

@property(nonatomic, strong)UIView *soundView;
@property(nonatomic, strong)UIImageView *soundImageView;
@property(nonatomic, strong)UILabel *timeLable;
@property(nonatomic, assign)NSInteger playflag;
@property(nonatomic, strong)UIButton *bcbdBtn;
@end

@implementation BXPersonDataVoiceVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavView];
    self.fd_prefersNavigationBarHidden = YES;

    [self SoundbackView];
    self.view.backgroundColor = [UIColor whiteColor];
    _playSound = [[DynPlayMp3Voice alloc]init];
    _playSound.delegate = self;
    
    if ([[BXAppInfo appInfo].is_dynamic_open intValue] != 0) {
    _bcbdBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_bcbdBtn];
    
    [_bcbdBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(__ScaleWidth(150));
        make.bottom.equalTo(self.view.mas_bottom).offset(-250);
        make.right.mas_equalTo(self.view.mas_right).offset(-(__ScaleWidth(12)));
        make.height.mas_equalTo(__ScaleWidth(20));
    }];
    [_bcbdBtn setTitle:NSLocalizedString(@"同步发布到动态", nil) forState:UIControlStateNormal];
    [_bcbdBtn setImage:CImage(@"public_icon_share_normal") forState:UIControlStateNormal];
    [_bcbdBtn setImage:CImage(@"public_icon_share_selected") forState:BtnSelected];
    [_bcbdBtn setTitleColor:sl_textColors];
    [_bcbdBtn.titleLabel setFont:SLPFFont(14)];
    [_bcbdBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, __ScaleWidth(15), 0, 0)];
    [_bcbdBtn addTarget:self action:@selector(saveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    MMKV *mmkv = [MMKV defaultMMKV];
    _bcbdBtn.selected = [mmkv getBoolForKey:@"ItemSaveKey"];
    }
    
//    如果设置过语音标签，要下载文件并展示
    BXLiveUser *lu = [BXLiveUser currentBXLiveUser];
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    WS(weakSelf);
    NSString *tempPath = [documentPath stringByAppendingPathComponent:@"mp3file/voice_sign.mp3"];
    NSError *error = nil;
    if ([[NSFileManager defaultManager] fileExistsAtPath:tempPath]) {
        [[NSFileManager defaultManager] removeItemAtPath:tempPath error:&error];
    }
    if (lu.voice_sign && ![lu.voice_sign isEqualToString:@""]) {
        [SLUpLoadAndDownloadTools downloadFileWithUrlString:lu.voice_sign filePath:tempPath success:^(NSDictionary *jsonDic, BOOL flag, NSMutableArray *models) {
            if (flag) {
//                下载成功
                weakSelf.soundView.hidden = NO;
                weakSelf.mp3Path = tempPath;
                [weakSelf.playSound StartPlayWithplaypath:tempPath];
                
                
            }
        } failure:^(NSError *error) {
        }];
    }

}
-(void)SoundbackView{
    _soundView = [[UIView alloc]init];
//    _soundView.backgroundColor = [UIColor cyanColor];
//    _soundView.layer.masksToBounds = YES;
//    _soundView.layer.cornerRadius = 16;
    [self.view addSubview:_soundView];
    [_soundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).offset(15);
        make.right.mas_equalTo(self.view.mas_right).offset(-15);
        make.height.mas_equalTo(39);
        make.top.mas_equalTo(self.navView.mas_bottom).offset(15);
    }];
    
    UIView *voiceView = [[UIView alloc]init];
    voiceView.backgroundColor = UIColorHex(#FF2D52);
    voiceView.layer.masksToBounds = YES;
    voiceView.layer.cornerRadius = 23;
    [self.soundView addSubview:voiceView];
    [voiceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.width.mas_equalTo(191);
    }];
    
    
    _timeLable = [[UILabel alloc]init];
    _timeLable.textColor = [UIColor whiteColor];
    _timeLable.font = [UIFont systemFontOfSize:14];
    _timeLable.text = @"00:00";
    _timeLable.textAlignment = 2;
    

    
    _soundImageView = [[UIImageView alloc]init];
    _soundImageView.image = [UIImage imageNamed:@"express_sound_note"];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(soundPlayAct)];
    _soundImageView.userInteractionEnabled = YES;
    [_soundImageView addGestureRecognizer:tap];
    [voiceView sd_addSubviews:@[_timeLable, _soundImageView]];
    _soundImageView.sd_layout.leftSpaceToView(voiceView, 20).topSpaceToView(voiceView, 10).bottomSpaceToView(voiceView, 10).widthIs(86);
    _timeLable.sd_layout.rightSpaceToView(voiceView, 20).widthIs(40).topSpaceToView(voiceView, 5).bottomSpaceToView(voiceView, 5);
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(RemoveSoundViewAct:) forControlEvents:UIControlEventTouchUpInside];
    [button setImage:CImage(@"dyn_issue_Del_addPic") forState:UIControlStateNormal];
    [_soundView addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(voiceView.mas_right).offset(15);
        make.centerY.mas_equalTo(voiceView.mas_centerY);
        make.height.width.mas_equalTo(21);
    }];
    
    BXPersonDataRecordVoiceView *recodeVoiceView = [[BXPersonDataRecordVoiceView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 250 - __kBottomAddHeight, self.view.frame.size.width, 250 + __kBottomAddHeight)];
    WS(weakSelf);
    recodeVoiceView.ReturnPath = ^(NSString * _Nonnull mp3Path) {

        if (!weakSelf.soundView.hidden) {
            BXDynAlertRemoveSoundView *view =[[BXDynAlertRemoveSoundView alloc]initWithFrame:CGRectMake(0, 0, __kWidth, __kHeight)Title:NSLocalizedString(@"是否替换当前录音", nil) Sure:NSLocalizedString(@"替换", nil) Cancle:NSLocalizedString(@"取消", nil)];
            view.RemoveBlock = ^{
                [weakSelf.playSound StartPlayWithplaypath:mp3Path];
                weakSelf.soundView.hidden = NO;
                weakSelf.mp3Path = mp3Path;
                [weakSelf.issueBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                weakSelf.issueBtn.backgroundColor = sl_normalColors;
                weakSelf.issueBtn.userInteractionEnabled = YES;
            };
            [weakSelf.view addSubview:view];
        }else{
            [weakSelf.playSound StartPlayWithplaypath:mp3Path];
            weakSelf.soundView.hidden = NO;
            weakSelf.mp3Path = mp3Path;
            [weakSelf.issueBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            weakSelf.issueBtn.backgroundColor = sl_normalColors;
            weakSelf.issueBtn.userInteractionEnabled = YES;
        }
    };
    [self.view addSubview:recodeVoiceView];
    
    _soundView.hidden = YES;
}

-(void)soundPlayAct{
    if (!_playflag) {
        [_playSound startPlay];
        [self rotateView];
        _playflag = 1;
    }else{
         [_playSound StopPlay];
        [self StoprotateView];
        _playflag = 0;
    }
}
-(void)ReturnDuratime:(NSString *)timeString{
    _timeLable.text = timeString;
}
-(void)getTime:(NSString *)timeString{
    _timeLable.text = timeString;
}

-(void)RemoveSoundViewAct:(id)sender{
    BXDynAlertRemoveSoundView *view =[[BXDynAlertRemoveSoundView alloc]initWithFrame:CGRectMake(0, 0, __kWidth, __kHeight)Title:NSLocalizedString(@"是否放弃当前录音", nil) Sure:NSLocalizedString(@"放弃", nil) Cancle:NSLocalizedString(@"取消", nil)];
    WS(weakSelf);
    view.RemoveBlock = ^{
        weakSelf.playflag = 0;
        weakSelf.mp3Path = @"";
        weakSelf.soundView.hidden = YES;
        [weakSelf.issueBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        weakSelf.issueBtn.backgroundColor = sl_normalColors;
        weakSelf.issueBtn.userInteractionEnabled = YES;
    };
    [self.view addSubview:view];
}

- (void)rotateView{
    [_soundImageView.layer removeAllAnimations];
    CABasicAnimation *rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.x"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI*2.0];
    rotationAnimation.duration = 1;
    rotationAnimation.repeatCount = HUGE_VALF;
    [_soundImageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
}
-(void)StoprotateView{
    [_soundImageView.layer removeAllAnimations];
}

- (NSString *)getFormatString:(NSInteger)totalSeconds {
    NSInteger seconds = totalSeconds % 60;
    NSInteger minutes = (totalSeconds / 60) % 60;
    NSInteger hours = totalSeconds / 3600;
    if (hours <= 0) {
        return [NSString stringWithFormat:@"%02ld:%02ld",(long)minutes, (long)seconds];
    }
    return [NSString stringWithFormat:@"%02ld:%02ld:%02ld",(long)hours, (long)minutes, (long)seconds];
}
#pragma - mark PlayDelegate
-(void)endPlaySound{
//    [_playSound StopPlay];
    [self StoprotateView];
}

-(void)setNavView{
    self.navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64+__kTopAddHeight)];
    self.navView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.navView];
    
   UILabel *_viewTitlelabel = [[UILabel alloc]init];
    _viewTitlelabel.text = NSLocalizedString(@"语音标签", nil);
    _viewTitlelabel.textColor = sl_blackBGColors;
    _viewTitlelabel.textAlignment = 1;
    _viewTitlelabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18];
    [_navView addSubview:_viewTitlelabel];
    
    _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backBtn setImage:CImage(@"nav_icon_back_black") forState:BtnNormal];
    _backBtn.contentMode = UIViewContentModeScaleAspectFit;
    [_backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navView addSubview:_backBtn];

    _issueBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [_issueBtn setImage:CImage(@"nav_icon_news_black") forState:BtnNormal];
    [_issueBtn setTitle:NSLocalizedString(@"保存", nil) forState:UIControlStateNormal];
    [_issueBtn setTitleColor:sl_textSubColors forState:UIControlStateNormal];
    _issueBtn.backgroundColor = sl_subBGColors;
    _issueBtn.userInteractionEnabled = NO;
//    [_issueBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    _issueBtn.backgroundColor = sl_normalColors;
    _issueBtn.layer.cornerRadius = __ScaleWidth(13);
    _issueBtn.layer.masksToBounds = YES;
    _issueBtn.contentMode = UIViewContentModeScaleAspectFit;
    _issueBtn.titleLabel.font = SLPFFont(__ScaleWidth(14));
    [self.navView addSubview:_issueBtn];
    [_issueBtn addTarget:self action:@selector(AddClick) forControlEvents:UIControlEventTouchUpInside];
    
    [_viewTitlelabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_navView);
        make.width.mas_equalTo(__ScaleWidth(72/4*6));
        make.height.mas_equalTo(25);
        make.centerY.equalTo(_navView.mas_bottom).offset(-22);
    }];
    [_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(__ScaleWidth(12));
        make.width.height.mas_equalTo(18.5);
        make.top.mas_equalTo(20 + __kTopAddHeight + 12);
    }];
    [_issueBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-12);
        make.width.mas_equalTo(__ScaleWidth(52));
        make.height.mas_equalTo(__ScaleWidth(26));
        make.top.mas_equalTo(20 + __kTopAddHeight + 12);
    }];

}
-(void)saveBtnClick:(UIButton *)sender{
    sender.selected = !sender.selected;

    MMKV *mmkv = [MMKV defaultMMKV];
    [mmkv setBool:sender.selected forKey:@"ItemSaveKey"];
    [mmkv sync];
}
-(void)AddClick{
    
    if (IsNilString(_mp3Path)) {
         WS(weakSelf);
         [[NewHttpManager sharedNetManager] POST:@"s=User.saveInfo" parameters:@{@"voice_sign":_mp3Path,@"is_synchro":@""} success:^(id  _Nonnull responseObject) {
                if ([responseObject[@"code"] integerValue] == 0) {
                    [BGProgressHUD hidden];
        //            更新成功
                    BXLiveUser *user = [BXLiveUser currentBXLiveUser];
                    user.voice_sign = responseObject[@"data"][@"voice_sign"];
                    [BXLiveUser setCurrentBXLiveUser:user];
                    [weakSelf pop];
                }else{
                    [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"设置失败", nil)];
                }
                
            } failure:^(NSError * _Nonnull error) {
                [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"设置失败", nil)];
            }];
        return;
    }
    
//    上传语音文件
    WS(weakSelf);
    [BGProgressHUD showLoadingAnimation];
    [SLUpLoadAndDownloadTools uploadFileWithType:@"friend_voice" filePath:self.mp3Path success:^(NSDictionary *jsonDic, BOOL flag, NSMutableArray *models) {
        NSLog(@"%@", jsonDic);
        /*
         {
             resultCode : 0,
             filePath : https://static.cnibx.cn/bingxin/friend/voice/b663acd9f95d8269df53599f9f0922f95df872cf.mp3
         }
         */
        if (flag) {
            MMKV *mmkv = [MMKV defaultMMKV];
           BOOL saveKey = [mmkv getBoolForKey:@"ItemSaveKey"];
            
            [[NewHttpManager sharedNetManager] POST:@"s=User.saveInfo" parameters:@{@"voice_sign":jsonDic[@"filePath"],@"is_synchro":[NSNumber numberWithBool:saveKey]} success:^(id  _Nonnull responseObject) {
                if ([responseObject[@"code"] integerValue] == 0) {
                    [BGProgressHUD hidden];
        //            更新成功
                    BXLiveUser *user = [BXLiveUser currentBXLiveUser];
                    user.voice_sign = responseObject[@"data"][@"voice_sign"];
                    [BXLiveUser setCurrentBXLiveUser:user];
                    if (weakSelf.complateBlock) {
                        weakSelf.complateBlock(jsonDic[@"filePath"]);
                    }
                    [weakSelf pop];
                }else{
                    [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"设置失败", nil)];
                }
                
            } failure:^(NSError * _Nonnull error) {
                [BGProgressHUD showInfoWithMessage:NSLocalizedString(@"设置失败", nil)];
            }];
        }else{
            [BGProgressHUD showInfoWithMessage:jsonDic[@"msg"]];
        }
    } failure:^(NSError *error) {
        [BGProgressHUD hidden];
    }];
}
-(void)backClick{
    [self pop];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
